<template>
  <div class="tag-container">
    <div>
      <template v-for="tag in tags">
        <a-tag :key="tag" :closable="true" @close="() => handleClose(tag)">
          {{ tag }}
        </a-tag>
      </template>
    </div>
    <a-input v-if="inputVisible" ref="input" type="text" size="small"
             :style="{ width: '78px',padding: '12px 0' }" :value="inputValue"
             @change="handleInputChange" @blur="handleInputConfirm" @keyup.enter.pervent="handleInputConfirm"
    />
    <a-tag v-else  @click="showInput" class="add-tag">
      添加标签
    </a-tag>
  </div>
</template>

<script>
  import GLOBAL from '@/api/global_variable'
  import axios from 'axios'
  export default {
    name: 'TagContainer',
    data () {
      return {
        tags: [],
        inputVisible: false,
        inputValue: '',
      };
    },
    mounted () {
      this.getLocalTags();
    },
    methods: {
      // 获取缓存的标签数;
      getLocalTags () {
        let tags = JSON.parse(localStorage.getItem('tags'));
        if (!tags) {
          tags = [];
        }
        this.tags = tags;
        this.$emit('tagChange', this.tags);
      },
      handleClose(removedTag) {
        const tags = this.tags.filter(tag => tag !== removedTag);
        console.log(tags);

        this.tags = tags;
        localStorage.setItem('tags', JSON.stringify(tags));
        this.$emit('tagChange', this.tags);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(function() {
          this.$refs.input.focus();
        });
      },

      handleInputChange(e) {
        this.inputValue = e.target.value;
      },

      handleInputConfirm() {
        const inputValue = this.inputValue;
        let tags = this.tags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        console.log(tags);
        // 将数据存入缓存中;
        localStorage.setItem('tags', JSON.stringify(tags));
        this.$emit('tagChange', tags);
        Object.assign(this, {
          tags,
          inputVisible: false,
          inputValue: '',
        });
      },
    }
  }
</script>

<style scoped="scoped">
  .tag-container .ant-tag {
    padding: 4px 6px !important;
    font-size: 13px;
  }
  .tag-container .add-tag {
    margin-top: 10px;
    padding: 4px 10px !important;
    font-size: 15px;
    font-weight: bold;
    background: #fff;
    border: 1px dashed #ccc;
  }

</style>
